package com.ktjy.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: DABINGCHNEGJIAO
 * @CreateTime: 2025-05-22
 * @Description: 返回和关闭SqlSession实例
 * @Version: 1.0
 */
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //1.加载MyBatis的配置文件
            String resource = "mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            //2.创建SqlSessionFactory对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException("初始化失败" + e);
        }
    }

    //3.创建SqlSession实例
    public static SqlSession createSqlSession() {
        return sqlSessionFactory.openSession(false); //关闭自动提交开启事务
    }

    //4.关闭SqlSession实例
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}
